package main

import (
	"data-treating/pkg/analysis"
	"data-treating/pkg/api"
	"log"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

func main() {
	// 初始化配置
	initConfig()

	// 初始化日志
	initLogger()

	// 创建姿势分析器
	analyzer := analysis.NewPoseAnalyzer()

	// 创建API处理器
	handler := api.NewHandler(analyzer)

	// 设置Gin模式
	if viper.GetString("app.mode") == "production" {
		gin.SetMode(gin.ReleaseMode)
	}

	// 创建路由
	router := gin.Default()

	// 设置中间件
	setupMiddleware(router)

	// 设置路由
	api.SetupRoutes(router, handler)

	// 启动服务器
	port := viper.GetString("server.port")
	if port == "" {
		port = "8080"
	}

	logrus.Infof("Starting server on port %s", port)
	if err := router.Run(":" + port); err != nil {
		logrus.Fatalf("Failed to start server: %v", err)
	}
}

// initConfig 初始化配置
func initConfig() {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")
	viper.AddConfigPath("./config")

	// 设置默认值
	viper.SetDefault("app.mode", "development")
	viper.SetDefault("server.port", "8080")
	viper.SetDefault("log.level", "info")

	// 读取环境变量
	viper.AutomaticEnv()

	// 读取配置文件
	if err := viper.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
			log.Printf("Error reading config file: %v", err)
		}
	}
}

// initLogger 初始化日志
func initLogger() {
	level := viper.GetString("log.level")
	logLevel, err := logrus.ParseLevel(level)
	if err != nil {
		logLevel = logrus.InfoLevel
	}

	logrus.SetLevel(logLevel)
	logrus.SetFormatter(&logrus.JSONFormatter{})

	// 设置输出
	if viper.GetString("app.mode") == "production" {
		logrus.SetOutput(os.Stdout)
	}
}

// setupMiddleware 设置中间件
func setupMiddleware(router *gin.Engine) {
	// 添加CORS中间件
	router.Use(func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// 添加日志中间件
	router.Use(gin.Logger())

	// 添加恢复中间件
	router.Use(gin.Recovery())
}
